<?php

namespace Beerus\Modules\PackageOrder\Controllers;

use App\Admin\Extensions\WorkContent;
use App\Exceptions\InputErrorException;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\model\package\PackageLogistics;
use Biz\model\package\PackageOrder;
use Biz\model\package\PackageOrderLog;
use Biz\service\trade\ShopCourier as sShopCourier;
use Biz\module\Packages\Logistics\TrackingMore;
use Doraemon\model\Article;
use Doraemon\model\DecorationTask\UserTaskDiary;
use Doraemon\model\Diary;
use Doraemon\model\Member;
use Doraemon\pockets\excel\DownExcel;
use Biz\service\package\OrderLogisticsLog;
use Doraemon\tools\ImgUrl;
use Doraemon\tools\Log;
use Doraemon\tools\ShopArea;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use hhz\constant\basic\UserExtendPhoneScene;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Redirector;
use Illuminate\Support\MessageBag;
use Doraemon\model\Phone;

class PackageOrderController
{
    public function index(Content $content, Request $request)
    {
        $params = $request->all();
        $where = $this->buildWhere($params);
        $page = $request->input('page', 1);
        $pageSize = $request->input('per_page', 20);
        $limit = [($page - 1) * $pageSize, $pageSize];
        $list = PackageOrder::getList($where, $limit);
        $total = PackageOrder::countNum($where);
        $list = $this->format($list);
        $gridModel = new pGridDataModel($list, $total, [
            'perPage' => $pageSize,
            'keyName' => 'goods_id'
        ]);
        $listGrid = Admin::grid($gridModel, function (Grid $grid) use ($where) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();
            $grid->expandFilter();
            $grid->disableActions();
            $grid->tools(function (Grid\Tools $tools) use ($where) {
                $downUrl = '/admin/packageOrder/order/downExcel?condition=' . base64_encode(json_encode($where));
                $tools->append("<a href='{$downUrl}' class='btn button-success'><i class='fa fa-file-excel-o'></i>>批量导出</a>");
            });
            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->expand();
                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('order_no', '订单号');
//                    $filter->equal('status', '订单状态')->select(PackageOrder::STATUS_MAP);
                    $filter->between('pay_time', '下单时间')->datetime();
                });
                $filter->column(1 / 2, function ($filter) {
//                    $filter->equal('package_id', '商品类型')->select(PackageOrder::PACKAGES);
                    $filter->dropDown('aaaa', [
                        'uid' => '用户ID',
                        'nick' => '用户昵称'
                    ]);
//                    $filter->equal('is_bad', '客诉订单')->select(PackageOrder::IS_BAD);

                });
            });

            $grid->column('order_no', '订单号');
            $grid->column('package_id', '商品类型')->display(function ($released) {
                return PackageOrder::PACKAGES[$released];
            });
            $grid->column('uid', 'uid');
            $grid->column('nick', '用户昵称');
            $grid->column('status', '订单状态');
            $grid->column('money', '支付金额');
            $grid->column('pay_way', '支付渠道')->display(function ($released) {
                if ($released == 'alipay') {
                    return '支付宝';
                } else if ($released == 'wechat_biz' || $released == 'wechat'){
                    return '微信';
                } else {
                    return '0元付';
                }
            });
            $grid->column('pay_time', '下单时间');

//            $grid->column('diary', '是否有符合条件日记');
//            $grid->column('house', '是否有符合条件整屋');
//            $grid->column('baggage', '未发货包裹数');
//            $grid->column('is_bad', '客诉订单')->display(function ($released) {
//                return PackageOrder::IS_BAD[$released];
//            });

            Admin::script($this->expressPopup());
            $grid->actions(function ($actions) {
                $actions->row->setKeyName('id');
                $actions->disableDelete();
                // 去掉编辑
                $actions->disableEdit();
//                $actions->prepend('<a href="edit' . '?all=' . base64_encode((string)json_encode($actions->row->getAttributes())) . '" > 查看详情 </a>');
//                $actions->prepend('<a class="express" data-phone="' . $actions->row->consignee_phone_encrypt . '" data-name="' . $actions->row->consignee_name . '" data-address="' . $actions->row->consignee_address . '" data-orderno="' . $actions->row->order_no . '" data-id="' . $actions->row->id . '" href="javascript:void(0);">&nbsp;收货地址&nbsp;</a>');
//                $actions->prepend('<a class="addExpress" data-id="' . $actions->row->id . '" data-package="' . $actions->row->package_id . '" data-company="' . $actions->row->express_company . '" data-fee="' . $actions->row->shipping_fee . '" data-logistics="' . $actions->row->order_logistics_no . '" data-nick="' . $actions->row->nick . '" data-order="' . $actions->row->order_no . '" href="javascript:void(0);">发货</a>');
            });
        });
        return $content
            ->header('新人大礼包订单列表')
            ->breadcrumb(['text' => '新人大礼包订单', 'url' => '/admin/packageOrder/order'])
            ->body($listGrid);
    }

    public function expressPopup()
    {
        return <<<SCRIPT
            $('.express').unbind('click').click(function() {
                var consignee_name = $(this).data('name');
                var consignee_phone_encrypt = $(this).data('phone');
                var address = $(this).data('address');
                var order_no = $(this).data('orderno');
                var id = $(this).data('id');
                //iframe窗
                layer.open({
                    type: 2,
                    title: '收货信息',
                    shadeClose: true,
                    shade: 0.4,
                    maxmin: true,
                    area: ['500px', '400px'],
                    content: 'address/'+id + '?consignee_phone_encrypt=' + consignee_phone_encrypt + '&consignee_name='+consignee_name + '&address='+address + '&order_no='+order_no,
                    end: function () {
                    }
                });
		    });
            $('.addExpress').unbind('click').click(function() {
                var id = $(this).data('id');
                var nick = $(this).data('nick');
                var order = $(this).data('order');
                var express_company = $(this).data('company');
                var order_logistics_no = $(this).data('logistics');
                var shipping_fee = $(this).data('fee');
                var package_id = $(this).data('package');
                //iframe窗
                layer.open({
                    type: 2,
                    title: '发货',
                    shadeClose: true,
                    shade: 0.4,
                    maxmin: true,
                    area: ['700px', '600px'],
                    content: 'addExpress/'+id + '?nick=' + nick + '&package_id='+package_id + '&order='+order + '&express_company='+express_company + '&order_logistics_no='+order_logistics_no + '&shipping_fee='+shipping_fee,
                    end: function () {
                    }
                });
		    });
SCRIPT;
    }

    //添加发货弹窗
    public function addExpress(Request $request, WorkContent $content, $id)
    {
        $request = $request->all();
        $tab = new Tab();
        if ($request['package_id'] == PackageOrder::PACKAGE_ID_1) {
            $request['goods_id'] = 1;
            $tab->add('包裹1', $this->addExpressAction($request, $id));
        } else {
            $request['goods_id'] = 1;
            $tab->add('包裹1', $this->addExpressAction($request, $id));
            $request['goods_id'] = 2;
            $tab->add('包裹2', $this->addExpressAction($request, $id));
            $request['goods_id'] = 3;
            $tab->add('包裹3', $this->addExpressAction($request, $id));
        }
        return $content
            ->header('发货')
            ->body($tab);
    }

    public function addExpressAction($request, $id)
    {
        $courierList = sShopCourier::getCourierFileList();
        $courier = [];
        $data['id'] = $id;
        $data['order_no'] = $request['order'];
        $data['express_company'] = $request['express_company'] ?: '';
        $data['order_logistics_no'] = $request['order_logistics_no'] ?: '';
        $data['nick'] = $request['nick'];
        $data['shipping_fee'] = $request['shipping_fee'];
        $data['goods_id'] = $request['goods_id'];
        foreach ($courierList as $item) {
            if (empty($item['trackingmore_code'])) {
                continue;
            }
            $key = $item['trackingmore_code'] . '~%~' . $item['courier_name'];
            $courier[$key] = $item['courier_name'];
            if ($item['courier_name'] == $data['express_company']) {
                $data['express_company'] = $key;
            }
        }

        $form = new Form($data);
        $form->hidden('id', 'id');
        $form->hidden('goods_id', 'goods_id');
        $form->hidden('nick', 'nick');
        $form->hidden('order_no', '订单号');
        $form->text('order_no', '订单号')->disable()->required();
        $form->text('nick', '昵称')->disable()->required();
        $form->number('shipping_fee', '实际运费')->required();
        $form->select('express_company', '物流公司')->required()->options($courier);
        $form->text('order_logistics_no', '物流单号')->required();
        $form->action('/admin/packageOrder/express/save');

        return $form->render();
    }

    public function address(Request $request, WorkContent $content)
    {
        $data['consignee_phone_encrypt'] = $request['consignee_phone_encrypt'];
        $data['address'] = $request['address'];
        $data['consignee_name'] = $request['consignee_name'];
        $data['order_no'] = $request['order_no'];
        $msg = '';
        if (!empty($logisticsInfo['logistics_info'])) {
            foreach ($logisticsInfo['logistics_info'] as $item) {
                $msg = $msg . "<p>" . $item['accept_station'] . $item['accept_time'] . "<p>" . "\r\n";
            }
        }
        $data['express'] = $msg;
        $form = new Form($data);
        $form->disableSubmit();
        $form->disableReset();
        $form->display('consignee_name', '收货人')->disable();
        $form->display('address', '收货地址')->disable();
        $form->display('consignee_phone_encrypt', '收货人手机号')->disable();
        return $content
            ->body($form->render());
    }


    public function buildWhere($params)
    {
        $where = [];
        // 把手机号转换为数字
        if (($params['consignee_phone_encrypt'])) {
            $phone = Phone::addExtendPhone($params['consignee_phone_encrypt'], UserExtendPhoneScene::NEW_USER_PACKAGE_CONSIGNEE_PHONE);
            $where['AND']['consignee_phone_encrypt'] = $phone;
        }
        if ($params['order_no']) {
            $where['AND']['order_no'] = $params['order_no'];
        }
        $addTime = $params['pay_time'];
        if ($addTime['start'] && $addTime['end']) {
            $start = $addTime['start'];
            $end = $addTime['end'];
            $where['AND']['pay_time[<>]'] = [strtotime($start), strtotime($end)];
        }
        if ($params['status']) {
            $where['AND']['status'] = $params['status'];
        }
        if ($params['package_id']) {
            $where['AND']['package_id'] = $params['package_id'];
        }
        if ($params['uid']) {
            $where['AND']['uid'] = $params['uid'];
        }
        if ($params['is_bad']) {
            $where['AND']['is_bad'] = $params['is_bad'];
        }
        if ($params['nick']) {
            $uid = Member::getUidByNick($params['nick']);
            $where['AND']['uid'] = $uid;
        }
        $where['ORDER'] = ['addtime' => 'DESC'];
        return $where;
    }

    /**
     * 详情页
     * @param Content $content
     * @param Request $request
     * @param int $id
     * @return Content
     */
    public function edit(Content $content, Request $request, int $id = 0)
    {
        $all = $request->all()['all'];
        $data = json_decode(base64_decode($all), true);
        $data['status'] = PackageOrder::STATUS_MAP[$data['status']];
        $packageId = $data['package_id'];
        $data['package_id'] = PackageOrder::PACKAGES[$packageId];
        $data['price'] = PackageOrder::PACKAGES_PRICE[$packageId];
        $goodName = [
            '1' => '需求分析助手,新装100问,装修告知书,开工御守+资料夹+冰箱贴*1',
            '2' => '配套冰箱贴',
            '3' => '入户门垫',
        ];
        // 查询商品
        $packageLogistics = PackageLogistics::selectByWhere(['order_no' => $data['order_no']]);
        // 查询物流信息
        $logisticsInfo = OrderLogisticsLog::selectInfoByOrderNo($data['order_no']);
        $goods = [];
        foreach ($packageLogistics as $key => $logistic) {
            $goods[$key] = "<p><strong>" . "包裹：".$goodName[$logistic['package_id']]."</strong><p>" . "\r\n".
                "<p><strong>" . "发货商品：".$logistic['goods_id']."</strong><p>" . "\r\n".
                "<p><strong>" . "物流公司：".$logistic['express_company']."</strong><p>" . "\r\n".
                "<p><strong>" . "物流单号：".$logistic['order_logistics_no']."</strong><p>" . "\r\n";
            $msg = '';
            if (!empty($logisticsInfo[$logistic['order_logistics_no']]['logistics_info'])) {
                foreach ($logisticsInfo[$logistic['order_logistics_no']]['logistics_info'] as $item) {
                    $msg = $msg . "<p>" . $item['accept_station'] . $item['accept_time'] . "<p>" . "\r\n";
                }
            }
            $goods[$key] .= $msg;
        }
        $data['goods0'] = $goods[0] ?? '';
        $data['goods1'] = $goods[1] ?? '';
        $data['goods2'] = $goods[2] ?? '';

        $data['express'] = $msg;
        $data['package_id_raw'] = $packageId;
        $form = new Form($data);
        $form->fieldset('订单基本信息', function (Form $form) {
            $form->display('order_no', '订单号');
            $form->select('status', '订单状态')->options(PackageOrder::STATUS_MAP)->disable();
            $form->display('nick', '用户昵称');
            $form->select('package_id', '商品类型')->options(PackageOrder::PACKAGES)->disable();
            $form->display('money', '支付金额');
            $form->display('pay_way', '支付渠道');
            $form->display('pay_time', '支付时间');
            if ($form->data()['package_id'] != '基础包') {
                $form->display('diary', '是否符合条件日记');
                $form->display('house', '是否符合条件整屋');
            }

            $form->display('baggage', '未发货包裹数');
        });

        $form->fieldset('收货信息', function (Form $form) {
            $consigneeProvince = ShopArea::locationCodeOfProvince('86');
            $consigneeCity = $form->data()['consignee_province'] > 0 ? ShopArea::locationCodeOfProvince($form->data()['consignee_province']) : [];
            $consigneeArea = $form->data()['consignee_city'] > 0 ? ShopArea::locationCodeOfProvince($form->data()['consignee_city']) : [];
            if ($form->data()['status'] == PackageOrder::STATUS_MAP[PackageOrder::STATUS_NORMAL]) {
                $form->text('consignee_name', '收货人');
                $form->text('consignee_phone_encrypt', '收货手机号');
                $form->select('consignee_province', '省份')->options($consigneeProvince)->load('consignee_city', route('order.area'));
                $form->select('consignee_city', '城市')->options($consigneeCity)->load('consignee_area', route('order.area'));
                $form->select('consignee_area', '区县')->options($consigneeArea);
                $form->text('consignee_info_address', '详细地址');
            } else {
                $form->display('consignee_name', '收货人');
                $form->display('consignee_phone_encrypt', '收货手机号');
                $form->select('consignee_province', '省份')->options($consigneeProvince)->disable();
                $form->select('consignee_city', '城市')->options($consigneeCity)->disable();
                $form->select('consignee_area', '区县')->options($consigneeArea)->disable();
                $form->text('consignee_info_address', '详细地址')->disable();
            }

        });

        if ($packageId == PackageOrder::PACKAGE_ID_1) {
            $form->fieldset('商品信息', function (Form $form) {
                $form->display('goods0', '包裹1');
            });
        } else {
            $form->fieldset('商品信息-包裹1', function (Form $form) {
                $form->display('goods0', '包裹1');
            });
            $form->fieldset('商品信息-包裹2', function (Form $form) {
                $form->display('goods1', '包裹2');
            });
            $form->fieldset('商品信息-包裹3', function (Form $form) {
                $form->display('goods2', '包裹3');
            });
        }

        $form->fieldset('备注信息', function (Form $form) {
            $form->text('remarks', '备注')->placeholder('不多于255字符');
            $form->radio('o_from_type', '订单来源')->options(PackageOrder::IS_BAD)->default(BlackOrder::O_FROM_TYPE_YOUZAN);

        });

        if ($data['id']) {
            $form->fieldset('订单操作', function (Form $form) use ($data) {
                Admin::script($this->offOrderJs($data['id']));
                if ($data['status'] == PackageOrder::STATUS_MAP[PackageOrder::STATUS_OFF]) {
                    $form->html('<span class="community_category btn btn-sm btn-success" >订单已关闭</span>');
                } else {
                    $form->html('<span class="community_category btn btn-sm btn-success" id="offOrder">关闭订单</span>');
                }
            });
        }

        $form->disableReset();
        $form->action('/admin/packageOrder/order/save?id=' . $data['id']);
        return $content->header('订单查看')
            ->breadcrumb(['text' => '订单列表', 'url' => 'packageOrder/order'], ['text' => '订单列表'])
            ->row($form->render());
    }

    public function offOrderJs($id)
    {
        return <<<SCRIPT
            $('#offOrder').unbind('click').click(function() {
            var id = {$id};
            let url = '/admin/packageOrder/changeOrderInfo';
            var that = $(this)
            let params = {
                id:id
            };
            var text = that.text();
            if(text == '订单已关闭'){
                layer.msg('订单已是关闭状态');
                return '';
            }
            swal({
                title: "确定关闭订单吗？",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确认",
                showLoaderOnConfirm: true,
                cancelButtonText: "取消",
                preConfirm: function() {
                   $.post(url, params , function (result) {              
                         if (result.status == 0){
                            layer.msg('操作失败');                              
                        } else {
                            that.text('订单已关闭')
                            layer.msg('操作成功');
                        }
                    });
                }
                });
            });
SCRIPT;
    }

    public function changeOrderInfo(Request $request)
    {
        $param = $request->all();
        $id = $param['id'];
        $where = ['id' => $id];
        $data['status'] = PackageOrder::STATUS_OFF;
        $res = PackageOrder::updateData($data, $where);
        if ($res) {
            $code = 1;
        } else {
            $code = 0;
        }
        return response()->json(compact('code'));
    }

    public function save(Request $request)
    {
        $params = $request->all();
        if (!empty($params['remarks']) && strlen($params['remarks']) > 255) {
            throw new InputErrorException('不能大于255字符', InputErrorException::DEFAULT_CODE, 'remarks');
        }
        if (!empty($params['consignee_info_address']) && strlen($params['consignee_info_address']) > 255) {
            throw new InputErrorException('不能大于255字符', InputErrorException::DEFAULT_CODE, 'consignee_info_address');
        }
        $adminName = Admin::user()->name;
        Log::info('订单修改用户收货地址', [$params, $adminName]);
        $province = ShopArea::locationId2Name($params['consignee_province']);
        $city = ShopArea::locationId2Name($params['consignee_city']);
        $area = ShopArea::locationId2Name($params['consignee_area']);
        $params['consignee_address'] = $province . $city . $area . $params['consignee_info_address'];
        $params['consignee_address'] = str_replace('市辖区', '', $params['consignee_address']);
        if (empty($params['consignee_name']) || empty($params['consignee_phone_encrypt']) || empty($params['consignee_province']) || empty($params['consignee_city']) || empty($params['consignee_area']) || empty($params['consignee_info_address']) || empty($params['consignee_address'])) {
            Log::info('package-order-log', [$params, '地址异常']);
            $error = new MessageBag([
                'title' => '参数不正确，请重试'
            ]);
            return back()->with(compact('error'))->withInput();
        }
        $phone = Phone::addExtendPhone($params['consignee_phone_encrypt'], UserExtendPhoneScene::NEW_USER_PACKAGE_CONSIGNEE_PHONE);
        $id = PackageOrder::editById($params['id'], ['remarks' => $params['remarks'], 'consignee_province' => $params['consignee_province'],
            'consignee_city' => $params['consignee_city'], 'consignee_area' => $params['consignee_area'],
            'consignee_info_address' => $params['consignee_info_address'], 'consignee_address' => $params['consignee_address']
            , 'consignee_name' => $params['consignee_name'], 'consignee_phone_encrypt' => $phone
        ]);


        if (empty($id)) {
            $error = new MessageBag([
                'title' => '保存失败，请重试'
            ]);
            return back()->with(compact('error'))->withInput();
        }
        $success = new MessageBag([
            'title' => '保存成功'
        ]);
        return redirect("/admin/packageOrder/order")->with(compact('success'));
    }

    /**
     * @param Request $request
     * @return RedirectResponse|Redirector|void
     * @throws InputErrorException
     * @throws \Exception
     */
    public function saveAddress(Request $request)
    {
        $params = $request->all();
        if (!empty($params['shipping_fee']) && $params['shipping_fee'] < 0) {
            throw new InputErrorException('不可小于0', InputErrorException::DEFAULT_CODE, 'shipping_fee');
        }
        if (empty($params['express_company']) || mb_strlen($params['express_company']) > 50) {
            throw new InputErrorException('请填写快递公司', InputErrorException::DEFAULT_CODE, 'express_company');
        }
        if (empty($params['order_logistics_no']) || mb_strlen($params['order_logistics_no']) > 50) {
            throw new InputErrorException('请填写正确快递单号', InputErrorException::DEFAULT_CODE, 'order_logistics_no');
        }
        $adminName = Admin::user()->name;
        Log::info('订单保存地址', [$params, $adminName]);
        $express = explode('~%~', $params['express_company']);

        $id = PackageOrder::editById($params['id'], ['status' => PackageOrder::STATUS_EXPRESS]);
        $packageId = \Biz\service\package\PackageOrder::getPackageIdByOrderNo($params['order_no']);
        $res = PackageLogistics::insertOrUpdate(['express_company' => $express[1], 'order_logistics_no' => $params['order_logistics_no'],
            'logistics_time' => time(), 'status' => PackageOrder::STATUS_EXPRESS, 'shipping_fee' => $params['shipping_fee'],
            'order_no' => $params['order_no'], 'goods_id' => $params['goods_id'], 'package_id' => $packageId]);
        if (empty($id) || empty($res)) {
            $error = new MessageBag([
                'title' => '保存失败，请重试'
            ]);
            return back()->with(compact('error'))->withInput();
        }
        // 调用物流发货接口
        $param = [
            'logistics_channel' => TrackingMore::LOGISTICS_CHANNEL_GOODS_PACKAGE,
            'lang' => 'cn'
        ];
        $result = TrackingMore::createTracking($express[0], $params['order_logistics_no'], $param);
        if ($result['meta']['code'] != 200 && !$result['meta']['type']) {
            $logText = 'trackingmore创建追踪失败 原因:' . $result['meta']['message'];
        } else {
            $logText = 'trackingmore订阅成功';
        }
        // 记录发货日志
        $logData = json_encode(['carrier_code' => $express[0], 'express_company' => $express[1], 'order_logistics_no' => $params['order_logistics_no']], JSON_UNESCAPED_UNICODE);
        $log = [
            'log_data' => $logData,
            'log_type' => PackageOrderLog::LOG_TYPE_1,
            'log' => $logText,
            'order_no' => $params['order_no'],
        ];
        $res = PackageOrderLog::add($log);
        $uid = \Biz\service\package\PackageOrder::getUidByOrderNo($params['order_no']);
        $data = [
            'uid' => $uid,
            'order_no' => $params['order_no'],
            'order_logistics_no' => $params['order_logistics_no'],
            'carrier_code' => $express[0],
        ];
        $OrderLogisticsLogRes = OrderLogisticsLog::add($data);
        if (empty($res) || empty($OrderLogisticsLogRes)) {
            $error = new MessageBag([
                'title' => '物流调用失败，请重试'
            ]);
            return back()->with(compact('error'))->withInput();
        }
        $success = new MessageBag([
            'title' => '保存成功'
        ]);
        $data = PackageOrder::getById($params['id']);
        $query = '?nick=' . $params['nick'] . '&order=' . $data['order_no'] . '&express_company=' . $data['express_company'] . '&order_logistics_no=' . $data['order_logistics_no'];
        return redirect("/admin/packageOrder/addExpress/{$params['id']}" . $query)->with(compact('success'));
    }


    public function downExcel(Request $request)
    {
        $params = $request->all();
        $where = $params['condition'];
        $downExcel = new DownExcel();
        $title = '批量导出';
        $downExcel->setFrontBold('1');
        $downExcel->setFileName($title);
        $downExcel->setTitle($title);
        $downExcel->setSheetTitle($title);
        $list = PackageOrder::getList(json_decode(base64_decode($where), true), [], ['uid', 'order_no',
            'remarks', 'status', 'package_id', 'consignee_info_address', 'pay_way',
            'consignee_phone_encrypt', 'consignee_name', 'pay_time', 'is_bad', 'consignee_address']);
        $list = array_values($list);
        $uids = array_column($list, 'uid');
        $userInfo = Member::getUserList($uids, true);
        $exportList = [];
        // todo 手机号加解密
        foreach ($list as $k => $item) {
            if ($item['package_id'] == PackageOrder::PACKAGE_ID_1) {
                $package = '基础包';
                $price = 69;
            } else {
                $package = '高级包';
                $price = 149;
            }
            $phone = Phone::getExtendPhone($item['consignee_phone_encrypt'], UserExtendPhoneScene::NEW_USER_PACKAGE_CONSIGNEE_PHONE);
            $exportList[$k]['order_no'] = $item['order_no'];
            $exportList[$k]['package'] = $package;
            $exportList[$k]['user_id'] = $item['uid'];
            $exportList[$k]['user_name'] = $userInfo[$item['uid']]['nick'] ?? '';
            $exportList[$k]['status'] = PackageOrder::STATUS_MAP[$item['status']];
            $exportList[$k]['price'] = $price;
            $exportList[$k]['pay_way'] = $item['pay_way'];
            $exportList[$k]['pay_time'] = $item['pay_time'] ? date('Y-m-d H:i:s', $item['pay_time']) : '';
            $exportList[$k]['is_bad'] = $item['is_bad'] == PackageOrder::IS_BAD_1 ? '是' : '否';
            $exportList[$k]['remarks'] = $item['remarks'];
            $exportList[$k]['consignee_name'] = $item['consignee_name'];
            $exportList[$k]['consignee_address'] = $item['consignee_address'];
            $exportList[$k]['consignee_phone_encrypt'] = $phone;
        }
        $head = [
            '订单号', '商品类型', '用户uid', '用户昵称', '订单状态', '支付金额', '支付渠道', '支付时间', '客诉订单', '备注', '收货人', '收货地址', '手机号'
        ];
        $downExcel->create($exportList, $head);
        return back();
    }

    private function format($list)
    {
        if (is_array($list) && !empty($list)) {
            $uids = array_column($list, 'uid');
            $orders = array_column($list, 'order_no');
            $userInfos = Member::getUsers($uids);
            $logisiticsNum = \Biz\model\package\PackageLogistics::getLogisticsCount($orders);
            foreach ($list as &$val) {

                if ($val['package_id'] == PackageOrder::PACKAGE_ID_1) {
                    $baggage = 1 - $logisiticsNum[$val['order_no']];
                } else {
                    $hasArticle = Article::get('aid', [
                        'uid' => $val['uid'],
                        'addtime[>]' => $val['pay_time'],
                        'status' => [Article::STATUS_WAIT_CHECK, Article::STATUS_SUCCESS, Article::STATUS_PRIVATE]
                    ]);
                    if ($hasArticle) {
                        $val['house'] = '是';
                    } else {
                        $val['house'] = '否';
                    }
                    $hasDiary = UserTaskDiary::get('id', ['uid' => $val['uid'], 'diary_status' => UserTaskDiary::STATUS_NORMAL, 'addtime[>]' => date("Y-m-d H:i:s", $val['pay_time'])]);
                    if ($hasDiary) {
                        $val['diary'] = '是';
                    } else {
                        $val['diary'] = '否';
                    }
                    $baggage = 3 - $logisiticsNum[$val['order_no']];
                }
                $phone = Phone::getExtendPhone($val['consignee_phone_encrypt'], UserExtendPhoneScene::NEW_USER_PACKAGE_CONSIGNEE_PHONE);
                $coverList = json_decode($val['cover_list'], true);
                $val['cover_list'] = ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $coverList[0], ImgUrl::IMAGE_SIZE_OP_ORI);
                $val['nick'] = $userInfos[$val['uid']]['nick'];
                $val['pay_time'] = $val['pay_time'] ? date('Y-m-d H:i:s', $val['pay_time']) : '';
                $val['consignee_phone_encrypt'] = $phone;
                $val['baggage'] = $baggage;
                $val['money'] = $val['price'];
                $val['status'] = PackageOrder::STATUS_MAP[$val['status']];
                if ($val['status'] == '待发货' && $val['package_id'] == 3) {
                    $val['status'] = '已完成';
                }
            }
            return $list;
        }
        return [];
    }

    public function area(Request $request)
    {
        $pid = $request->input('q', 0);
        if (empty($pid)) {
            return response()->json([]);
        }
        $data = ShopArea::locationCodeOfProvince($pid);
        $format = array_map(function ($k, $v) {
            return [
                'id' => $k,
                'text' => $v,
            ];
        }, array_keys($data), $data);
        $format = array_merge([['id' => '', 'text' => '']], $format);
        return response()->json($format);
    }

}